<?php

defined('_JEXEC') or die;

$lang =& JFactory::getLanguage();

$session_vipcard =& JFactory::getSession();
$session_vipcard_id =  $session_vipcard->getId();

$item = $this->model;
$lang =& JFactory::getLanguage();

$item->name = unserialize($item->name);
$item->name = $item->name[$lang->getTag()];
 
$item->des = unserialize($item->des);
$item->des = $item->des[$lang->getTag()];

$quality = $quality_cash = 1;

if(count($this->cookie_items) > 0){
	foreach ($this->cookie_items as $citem){
		if($citem->id == $item->id){
			if($citem->type == 2)
				$quality_cash = $citem->qty;
			if($citem->type == 1)
				$quality = $citem->qty;
		}
		else{
			continue;
		}
	}
}

/*** Check display cash  ***/
$show = false;
if($item->cash > 0) $show = true;

$page_heading = $item->name;
$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
$document = &JFactory::getDocument();
$document->setTitle($title) ;

?>
<script src="<?php echo JURI::base(); ?>js/spin/jquery-spin.js"></script>
<script src="<?php echo JURI::base(); ?>js/jquery.cookie.js"></script>
<script src="<?php echo JURI::base(); ?>js/json_encode.js"></script>
<script src="<?php echo JURI::base(); ?>js/json_decode.js"></script>
<script src="<?php echo JURI::base(); ?>js/number_format.js"></script>

<script type="text/javascript">
	var scItems = [];

    if(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>") != ""){
       var data_dec = decodeCookies(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>"));
        scItems = json_decode(data_dec);
    }
    
    var currentUserPoint = "<?php echo $this->userPoint; ?>";    
    var totalPointSubtract = currentUserPoint;
    
    jQuery(function(){
    	
    	jQuery('.way_check').click(function(){
 			
		 	 if( jQuery(this).is(":checked") ){ // check if the radio is checked
		        var val = $(this).val(); // retrieve the value
		       if(val == 2){
		     		jQuery('.pointonly').hide();
		     		jQuery('.point_cash').show();
		       }
		       else{
		       		jQuery('.pointonly').show();
		     		jQuery('.point_cash').hide();
		       }
		    }
	 	});
    	
    	totalPointAndCash();

        jQuery(".extra-add-to-cart a").click(function(index){
            
            /**** Init params ****/
            var objName = jQuery(this).attr("name");
            var item = {
                id:     0,
                qty:    0,
                pcode:  0,
                type:   1,
                img:    '',
                point:  0,
                pointx: 0,
                cash:   0,
                name:   '',
				ptotal: 1
            };
            
            params = objName.split("_");
            item.id = params[1];
            var inputName = jQuery("input[name="+objName+"_type]:checked").attr("id");
            
            item.type = jQuery("#"+inputName).val();
            
            if(jQuery("input[name="+objName+"_type]:checked").length == 0){
                
                jQuery('#error_message').html('<p><?php echo JText::_('WRD_PROFILE_ALERT_PLEASE_CHOOSE_REDEMPTION_TYPE'); ?></p>');
                jQuery('#errorModal').modal('show');
                return false;
            }
            else {
                var qty = jQuery("input[name="+inputName+"_qty]").val();
                console.log(inputName);
                var productPoint = 0;
                if(item.type == 1) {
                    item.point = jQuery("#"+inputName+"_point").val();  
                    item.cash = 0;
                    item.pointx = 0;
                    productPoint = (parseInt(qty)*parseInt(item.point));
                }
                else {
                    item.point = 0;
                    item.pointx = jQuery("#"+inputName+"_pointx").val();
                    item.cash = jQuery("#"+inputName+"_cash").val();  
                    productPoint = (parseInt(qty)*parseInt(item.pointx));  
                }
                if(qty <= 0){                    
                    jQuery('#error_message').html('<p><?php echo JText::_('WRD_PROFILE_ALERT_PLEASE_INPUT_VALID_VALUE'); ?></p>');
                    jQuery('#errorModal').modal('show');
                    
                    jQuery("input[name="+inputName+"_qty]").focus();
                    return false;
                }
                else {
                    var subtractPoint = 0;
                    if(scItems != undefined && scItems.length > 0){
                        for(var i=0; i<scItems.length; i++){
                            if(item.id == scItems[i].id){
                                totalPointSubtract = parseInt(totalPointSubtract) + (parseInt(scItems[i].qty)*parseInt(scItems[i].type == 1 ? scItems[i].point : scItems[i].pointx));
                            }
                        }
                    }
                    var subtractPoint = totalPointSubtract;
                    subtractPoint = parseInt(subtractPoint)-parseInt(productPoint);
                        
                    if(subtractPoint < 0){
                        jQuery('#error_message').html('<p><?php JText::_('WRD_PROMOTION_YOUR_POINT_IS'); ?> "+(totalPointSubtract)+" < "+productPoint+" <?php echo JText::_('WRD_PROMOTION_IS_NOT_ENOUGHT_TO_REDEEM'); ?></p>');
                        jQuery('#errorModal').modal('show');
                    }
                    else {
                        //console.log(objName);
                        item.qty = qty;
                        item.img = jQuery("#"+objName+"_img").attr("src");
                        item.pcode = jQuery("#"+objName+"_code").html();
                        item.name = inputName;
                        
                      
                        var update = true;
                        var ptotal = 0;
                        var oldqty = 1;
						
                         if(scItems != undefined && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].id == item.id) {
                                        if(scItems[i].type != item.type) {
                                           update = false;
                                        }else{
											oldqty = scItems[i].qty;
                                            scItems[i] = item;
                                            update = true;
                                            break;
                                        }
                                    }else{
                                        update = false;
                                    }
                                }
                            }
                            
                            if(update == false ) {
                                scItems.push(item);
                            }
                        }
                        else {
                            
                        	if(scItems ==  null){
                                scItems = new Array();
                                scItems[0] = item;
                            } else {
                                scItems.push(item);    
                            }
                            
                        }
                    }
                }
            }   
            
			for(var i=0; i<scItems.length; i++){
                if(scItems[i].id == item.id) {
                    ptotal = ptotal + parseInt(scItems[i].qty);
                }
            }
			
			item.ptotal = ptotal;
			page_refresh = false;

            jQuery.ajax({
				async: false,
                type: "post",
                url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=addtocart&view=redemptions'); ?>",
                data: "params="+json_encode(item),
                success: function(json){
                    var result = eval(json);
                   	
                    if (result.success == true){

                        totalPointAndCash();
                        
                        jQuery('#cartModal').modal('toggle').on('shown.bs.modal', function (e) {
                            myModal = jQuery('#cartModal');
                            clearTimeout(myModal.data('hideInteval'))
                            var id = setTimeout(function(){
                                myModal.modal('hide');
                            },1000);
                            myModal.data('hideInteval', id);
                        });
                    }
                    else
                    {
                        if(result.refresh == true) page_refresh = true;
                    	if(scItems != null && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type == item.type){
                                    	//console.log(scItems[i]);
                                        scItems[i].qty = oldqty;
                                        jQuery("input[name="+scItems[i].name+"_qty]").val(scItems[i].qty);
                                    }
                                }
                            }
                        }
						
						if(result.html != ''){
							jQuery('#error_message').html('<p>'+result.html+'</p>');
							jQuery('#errorModal').modal('show');
						}
                    }
                }
                
                
            }); 
            
			var data_enc = encodeCookies(scItems);
            jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });   
			totalPointAndCash();
			
			if(page_refresh == true){
            	location.reload(true);
            }
            return true;
        });
});

function encodeCookies(obj){
		var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=encryptcart'); ?>",
            data: "params="+json_encode(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('security hole');
                }
            }
        });
        
        return data;
    }
	
	function decodeCookies(obj){
    	var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=decryptcart'); ?>",
            data: "params="+(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('can not decrypt');
                }
            }
        });
        return data;
    }
	
    function totalPointAndCash(){
        var totalPoint = 0;
        var totalCash = 0;
        if(scItems != undefined && scItems.length > 0){
        	var total_item = 0;
        	//console.log(scItems);
            for(var i=0; i<scItems.length; i++){
                
                totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
                totalCash = parseInt(totalCash) + parseInt(scItems[i].cash)*parseInt(scItems[i].qty);
                total_item = total_item + parseInt(scItems[i].qty);
                //console.log(parseInt(scItems[i].qty));
            }

            totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
            jQuery(".cart-detail").show();
            jQuery(".navbar-right .fa-shopping-cart").html('<span class="badge badge-num">'+total_item+'</span>');

        }else{

            jQuery(".cart-detail").hide();
        }
    }
    
</script>
<h4>
    <?php echo $item->name; ?>
</h4>
<form role="form"> 
<div id="productdetail" class="panel panel-default item-details panel-point-wmc">
    <div class="panel-heading panel-heading-img">
        <?php if($this->gallery != NULL): ?>
            <div id="product-carousel-generic" class="carousel slide" data-ride="carousel">
                 <div class="carousel-inner">
                    <?php  foreach ($this->gallery as $key => $value): ?>
                    <div class="item <?php echo $key == 0 ? 'active' : '' ?>">
                      <img src="<?php echo JURI::base(); ?>wrd/image/<?php echo $value->image; ?>">
                    </div>
                    <?php endforeach; ?>
                </div>
                <a class="left carousel-control" href="#product-carousel-generic" data-slide="prev">
                    <span class="glyphicon glyphicon-chevron-left"></span>
                </a>
                <a class="right carousel-control" href="#product-carousel-generic" data-slide="next">
                    <span class="glyphicon glyphicon-chevron-right"></span>
                </a>
            </div>
        <?php endif;?>
    </div>
	<div class="product panel-body">	  
	      
	    <br>
        <p><strong><?php echo JText::_('WRD_PROMOTION_PRODUCT_DETAIL'); ?></strong></p>
        <div class="contenttomtat">
            <?php echo $item->des; ?>
            <img style="display: none"
              id="extra-item_<?php echo $item->id ?>_img" 
              alt="<?php echo $item->name ?>" 
              title="<?php echo $item->name ?>" 
              src="<?php echo JURI::base().'wrd/image2/'.$item->image; ?>">
              
             
            
        </div>
        <br>
		
		    <div class="form-group">    
                <p><strong><?php echo JText::_('WRD_PROMOTION_WAY_CHECK') ?></strong></p>
    			
        		<?php if($item->point > 0): ?>
        		    <br>
        		    <label class="btn btn-default btn-block btn-fltlft way_check">
                	   <input <?php echo $show == false ? 'checked' : ''; ?> 
                	   class="way_check" checked="checked" type="radio" 
                	   name="extra-item_<?php echo $item->id; ?>_type" 
                	   id="extra-item_<?php echo $item->id; ?>_id" value="1" />
               	 	  <?php echo number_format($item->point,0,',',','); ?> 
               	 	  <?php echo JText::_('WRD_PROMOTION_POINTS') ?>
               	 	</label>
                <?php endif; ?>
                <?php if($show == true): ?>
                    <br>
            		<label class="btn btn-default btn-block btn-fltlft way_check">
                    	<input checked class="way_check" type="radio" 
                    	name="extra-item_<?php echo $item->id; ?>_type" 
                    	id="extra-item_<?php echo $item->id ?>_id_2" 
                    	value="2" />
                    	<?php echo number_format($item->pointx,0,',',','); ?> points + <?php echo number_format($item->cash,0,',',','); ?> <?php echo JText::_('WRD_PROMOTION_VND') ?>
            		</label>
        		<?php endif; ?>
			</div>
			
			<div class="form-group">
			    <p><strong><?php echo JText::_('WRD_PROMOTION_QUANTITY') ?></strong></p>
			    
    			<div class="pointonly" style="display:<?php echo $show == true ? 'none' : 'block' ?>">
    			    <div class="input-group">
        			    
                        <span class="input-group-btn">
                            <button class="btn btn-default" id="quality-num-add-" type="button"><strong>-</strong></button>
                        </span>
                        <input type="number" disabled="" class="form-control" id="quality-num" min="1"  name="extra-item_<?php echo $item->id; ?>_id_qty" value="<?php echo $quality; ?>" />
                        <input type="hidden" id="extra-item_<?php echo $item->id ?>_id_point" value="<?php echo $item->point ?>" />
                        <input type="hidden" id="extra-item_<?php echo $item->id ?>_id_pointx" value="<?php echo $item->pointx ?>" />
                        <input type="hidden" id="extra-item_<?php echo $item->id ?>_id_cash" value="<?php echo $item->cash ?>" />
                        <span class="input-group-btn">
                            <button class="btn btn-default" id="quality-num-add" type="button"><strong>+</strong></button>
                        </span>
                    </div>
                </div>
                
                <div class="point_cash" style="display:<?php echo $show == true ? 'block' : 'none' ?>">
                    <div class="input-group">
                        <span class="input-group-btn">
                            <button class="btn btn-default" id="extra-quality-num-add-2-" type="button"><strong>-</strong></button>
                        </span>
                        
                        <input type="number" class="form-control" id="extra-quality-num" min="1" name="extra-item_<?php echo $item->id ?>_id_2_qty"  value="<?php echo $quality_cash; ?>" />
                        <input type="hidden" id="extra-item_<?php echo $item->id ?>_id_2_point" value="<?php echo $item->point ?>" />
                        <input type="hidden" id="extra-item_<?php echo $item->id ?>_id_2_pointx" value="<?php echo $item->pointx ?>" />
                        <input type="hidden" id="extra-item_<?php echo $item->id ?>_id_2_cash" value="<?php echo $item->cash ?>" />
                        
                        
                        <span class="input-group-btn">
                            <button class="btn btn-default" id="extra-quality-num-add-2" type="button"><strong>+</strong></button>
                        </span>
                    </div>
                </div>
			</div>

             <div class="true_price help-block pull-right">
                <?php echo JText::_('WRD_PROMOTION_REF_PRICE') ?> <?php echo number_format($item->price,0,',',','); ?> <?php echo JText::_('WRD_PROMOTION_VND') ?>
            </div>

	 </div>
	 <div class="panel-heading">
        <?php if($item->quantity == 0): ?>
            <div class="fright pull-right" style="float: right; color: red;"><b>
                <i>(<?php echo JText::_('WRD_PROMOTION_OUT_OF_STOCK'); ?>)</i></b></div>
        <?php else: ?>
            <?php if($this->user->id == 0): ?>
                <div class="add-to-cart pull-right"><a id="submit" class="need_login" 
                    name="item_<?php echo $item->id; ?>" href="javascript:void(null);">
                    <i class="fa fa-shopping-cart"><span class="badge badge-add">+</span></i>
                    </a></div>
            <?php else: ?>
                <div class="extra-add-to-cart add-to-cart pull-right"><a id="submit" 
                    name="extra-item_<?php echo $item->id; ?>" href="javascript:void(null);">
                    <i class="fa fa-shopping-cart"><span class="badge badge-add">+</span></i></a></div>
            <?php endif;?>
        <?php endif; ?>
        <br clear="all">
	 </div>
</div>
</form>